﻿namespace _169多数元素
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Solution.MajorityElement(new int[] { 2, 2, 1, 1, 1, 2, 2 });
            Console.WriteLine(Solution2.MajorityElement(new int[] { 2, 2, 1, 1, 1, 2, 2 }));
        }
    }
    /*  
     * 给定一个大小为 n 的数组 nums ，返回其中的多数元素。多数元素是指在数组中出现次数 大于 ⌊ n/2 ⌋ 的元素。你可以假设数组是非空的，并且给定的数组总是存在多数元素。输入：nums = [2,2,1,1,1,2,2] 输出：2
     */
    public class Solution
    {
        public static int MajorityElement(int[] nums)
        {
            Dictionary<int, int> keyValuePairs = new Dictionary<int, int>();
            for (int i = 0; i < nums.Length; i++)
            {
                if (keyValuePairs.ContainsKey(nums[i]))
                {
                    keyValuePairs[nums[i]]++;
                }
                else
                {
                    keyValuePairs.Add(nums[i], 1);
                }
            }
            List<int> arr = new List<int>();
            foreach (var item in keyValuePairs.Values)
            {
                arr.Add(item);
            }
            arr = arr.OrderByDescending(x => x).ToList();
            var keys = keyValuePairs.Where(pair => pair.Value == arr[0])
                                 .Select(pair => pair.Key);
            foreach (var key in keys)
            {
                Console.WriteLine("Key: " + key);
            }
            return 0;
        }
    }

    public class Solution2
    {
        public static int MajorityElement(int[] nums)
        { 
            int count = 0;
            int candidate = 0;
            foreach (int num in nums)
            {
                if (count == 0)
                {
                    candidate = num;
                }
                count += (num == candidate) ? 1 : -1;
            }
            return candidate;
        }
    }
}